package com.xxkk.spring_boot_web.sdk.FaceBook;

import com.facebook.ads.sdk.APIContext;
import com.facebook.ads.sdk.APIException;
import com.facebook.ads.sdk.serverside.ActionSource;
import com.facebook.ads.sdk.serverside.Content;
import com.facebook.ads.sdk.serverside.CustomData;
import com.facebook.ads.sdk.serverside.DeliveryCategory;
import com.facebook.ads.sdk.serverside.Event;
import com.facebook.ads.sdk.serverside.EventRequest;
import com.facebook.ads.sdk.serverside.EventResponse;
import com.facebook.ads.sdk.serverside.UserData;
import com.xxkk.spring_boot_web.utils.HttpUtils;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.*;

import org.apache.commons.codec.binary.Hex;

/**
 * @author xxkk
 * @version 1.0.0
 * @title FaceBook
 * @description ʕ•ᴥ•ʔ
 * @create 2025/1/10 09:55
 **/
public class FaceBook {
    //facebook access_token 查询用户id
    //https://graph.facebook.com/me?access_token=xxx
    public static String getUserId(String access_token) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", access_token);
        String url = "https://graph.facebook.com/me";
        return HttpUtils.doGet(url, paramMap);
    }

    private static final UserData userData = new UserData()
            .emails(Arrays.asList("joe@eg.com"))
            .phones(Arrays.asList("12345678901", "14251234567"))
            // It is recommended to send Client IP and User Agent for Conversions API Events.
            .clientIpAddress("192.19.9.9")
            .clientUserAgent("test ua")
            .fbc("fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890")
            .fbp("fb.1.1558571054389.1098115397");

    public void postEvent(String PIXEL_ID, String ACCESS_TOKEN, String eventName) {
        Event ev = new Event();
        ev.eventName(eventName)
                .eventTime(System.currentTimeMillis() / 1000L)
                .userData(userData)
//                .customData(customData)
//                .eventSourceUrl("http://jaspers-market.com/product/123")
                .actionSource(ActionSource.website);

        EventRequest eventRequest = new EventRequest(PIXEL_ID, getApiContext(ACCESS_TOKEN));
        eventRequest.addDataItem(ev);
        try {
            EventResponse response = eventRequest.execute();
            System.out.println(String.format("Standard API response : %s ", response));
        } catch (APIException e) {
            e.printStackTrace();
        }
    }

    private synchronized static APIContext getApiContext(String ACCESS_TOKEN) {
        if (context_ == null || !context_.getAccessToken().equals(ACCESS_TOKEN))
            context_ = new APIContext(ACCESS_TOKEN);
        return context_;
    }

    private static APIContext context_ = null;

    //            new APIContext(
//            "{access-token}",
//            "{appsecret}"
//    );
    public static void main(String[] args) {
//        String ACCESS_TOKEN = "";
//        String PIXEL_ID = "";
//        APIContext context = new APIContext(ACCESS_TOKEN).enableDebug(true);
////        context.setLogger(System.out);
//
//        UserData userData = new UserData()
//                .emails(Arrays.asList("joe@eg.com"))
//                .phones(Arrays.asList("12345678901", "14251234567"))
//                // It is recommended to send Client IP and User Agent for Conversions API Events.
//                .clientIpAddress("192.19.9.9")
//                .clientUserAgent("test ua")
//                .fbc("fb.1.1554763741205.AbCdEfGhIjKlMnOpQrStUvWxYz1234567890")
//                .fbp("fb.1.1558571054389.1098115397");
//
//        Content content = new Content()
//                .productId("product123")
//                .quantity(1L)
//                .deliveryCategory(DeliveryCategory.home_delivery);
//
//        CustomData customData = new CustomData()
//                .addContent(content)
//                .currency("usd")
//                .value(123.45F);
//
//        Event purchaseEvent = new Event();
//        purchaseEvent.eventName("Purchase")
//                .eventTime(System.currentTimeMillis() / 1000L)
//                .userData(userData)
//                .customData(customData)
//                .eventSourceUrl("http://jaspers-market.com/product/123")
//                .actionSource(ActionSource.website);
//
//        EventRequest eventRequest = new EventRequest(PIXEL_ID, context);
//        eventRequest.addDataItem(purchaseEvent);

        try {
//            EventResponse response = eventRequest.execute();
//            System.out.println(String.format("Standard API response : %s ", response));
            String em = generateRandomPhoneNumber();
            System.out.println(String.format("%s # %s ", em, hashData(em)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String hashData(String data) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashedBytes = digest.digest(data.trim().getBytes(StandardCharsets.UTF_8));
            return Hex.encodeHexString(hashedBytes);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String generateRandomPhoneNumber() {
        // 创建Random对象
        Random random = new Random();

        // 手机号的第一位数字固定为1
        StringBuilder phoneNumber = new StringBuilder("1");

        // 手机号的第二位数字可以是3、4、5、6、7、8、9中的一个
        int secondDigit = random.nextInt(7) + 3; // 3到9之间的随机数
        phoneNumber.append(secondDigit);

        // 手机号的后面9位是任意数字
        for (int i = 0; i < 9; i++) {
            int randomDigit = random.nextInt(10); // 0到9之间的随机数
            phoneNumber.append(randomDigit);
        }

        return phoneNumber.toString();
    }

}
